//app.js
var http = require("./utils/util.js");
var Crypto = require('./utils/cryptojs/cryptojs.js').Crypto;
const recorderManager = wx.getRecorderManager();
const app = getApp()
App({
  netWorkData:{
    result:{code:-1,msg:"请求失败"} ,
    isreq:false, 
  },
  onLaunch: function () {
    var that = this;
    console.log("App OnLaunch")
    wx.getUserInfo({
      success: function (user) {
        console.log(user)
        that.globalData.userInfo = user.userInfo
      }
    })
    wx.getStorage({
      key: 'token',
      success: function(res) {
        that.globalData.token = res.data;
      },
    })
  },
  globalData: {
    userInfo: [],
    balance:[],
    token:'',
    // localApi:"https://www.hifun.cc/api/wxSDK",
    localApi:"https://www.3gosp.top/api/wxSDK",
  },
  // 登录
  login:function(){
    var that = this;
    console.log("执行login")
    wx.login({
      success: res => {
        console.log(res)
        console.log(that.globalData.localApi)
        that.globalData.code = res.code;
        var user;
        wx.getUserInfo({
          success:function(user){
            console.log("执行getCode") 
            user = user;
            that.globalData.userInfo = user.userInfo;
            wx.request({
              url:that.globalData.localApi+"/user/getCode",
              method:"get",
              data:{
                code:res.code,
                userInfo:user.userInfo,
              },
              success:function(res){
                console.log(res)
                wx.setStorage({
                  key: 'token',
                  data: res.data.data.token,
                })
                console.log("balance")
                that.balance();
              },
              fail:function(res){
                // that.showInfo("获取用户信息失败")
              }
            })
          }
        })    
        console.log(res)
        console.log(res.code);
      }
    })
  },

  // 请求余额
  balance: function () {
    var that = this;
    wx.getStorage({
      key: 'token',
      success: function (res) {
        var token = res.data;
        var timestamp = that.timestamp();
        var url = that.globalData.localApi + "/user/balance";
        var data = {
          timestamp: timestamp,
          token: token,
          sign: Crypto.MD5(that.sign(url, token, timestamp)),
          url:that.urlStr(url)
        };
        wx.request({
          url: url,
          method: "POST",
          data: data,
          success: function (res) {
            console.log(res.data)
            that.globalData.balance = res.balance;
            // that.setData({
            //   balance: res.data.data,
            // })
          },
        })
      },
    })
  },
  // 错误处理；
  err:function(code){
    var that = this;
    switch(code){
      case "-1":
        that.showInfo("信息错误")
      case "2001":
        that.login();
    }
  },
  // 提示信息；
  showInfo:function(content){
    wx.showModal({
      title:"提示信息",
      content:content,
      showCancel:false,
      success:function(res){
      }
    })
  },
// 提示信息TOast;
  showToast:function(title){
    wx.showToast({
      title: title,
      duration:1500,
    })
  },
  // 时间戳
  timestamp: function () {
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    return (timestamp)
  },
  // 签名加密
  sign: function (url, token, timestamp) {
    var sign = url.substring(url.search(/\/api\//g)).replace(/\//g, '/') + token + timestamp;
    return sign;
  },
  urlStr:function(url){
    var url = url.substring(url.search(/\/api\//g)).replace(/\//g, '/') ;
    return url;
  },
  // 判断是否位汉字
  checkChinese:function(val){
    var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
    var str = reg.test(val);
    return str
  },
  // checkChinese: function (dom, maxLength) {
  //   var l = 0;
  //   for (var i = 0; i < dom.length; i++) {
  //     if (/[\u4e00-\u9fa5]/.test(dom.value[i])) {
  //       l += 2;
  //     } else {
  //       return true;
  //     }
  //     if (l > maxLength) {
  //       dom = dom.substr(0, i);
  //       return dom;
  //     }
  //   }
  // },
  // 获取录音
  getVoice:function(){
    var that = this;
    // 开始录音的动画
    // this.setData({
    //   isSpeaking: true,
    // })
    // that.speaking();
    console.log("开始录音")
    const options = {
      duration: 60000,//指定录音的时长，单位 ms
      sampleRate: 16000,//采样率
      numberOfChannels: 1,//录音通道数
      encodeBitRate: 96000,//编码码率
      format: 'mp3',//音频格式，有效值 aac/mp3
      frameSize: 50,//指定帧大小，单位 KB
    }
    //开始录音
    recorderManager.start(options);
    recorderManager.onStart(() => {
      console.log('recorder start')
    });
    //错误回调
    recorderManager.onError((res) => {
      console.log(res);
    })
  },
  getVoiceEnd:function(){
    var that = this;
    recorderManager.stop();
    recorderManager.onStop((res) => {
      // this.tempFilePath = res.tempFilePath;
      console.log('停止录音', res.tempFilePath)
      // const { tempFilePath } = res
      that.uploadVoice(res.tempFilePath);
    })
  },
  formId:function(formId){
    var that = this;
    wx.getStorage({
      key: 'token',
      success: function(res) {
        var token = res.data;
        var url = that.globalData.localApi +"/user/formid";
        var timestamp = that.timestamp();
        wx.request({
          url: url,
          method:"POST",
          data:{
            url:that.urlStr(url),
            token:token,
            timestamp:timestamp,
            sign:Crypto.MD5(that.sign(url,token,timestamp)),
            formId: formId
          },
          success:function(){
            console.log("formId上传成功")
          }
        })
      },
    })
  },
  uploadUserInfo:function(){
    var that = this;
    console.log("uoloadUSer")
    wx.getStorage({
      key: 'token',
      success: function(res) {
        wx.getUserInfo({
          success:function(user){
            console.log(res)
            var url = that.globalData.localApi + "/user/info";
            var userInfo = user.userInfo;
            var token = res.data;
            var timestamp= that.timestamp();
            wx.request({
              url: url,
              method:"POST",
              data:{
                url:url,
                token:token,
                timestamp:timestamp,
                sign:Crypto.MD5(that.sign(url,token,timestamp)),
                url:that.urlStr(url),
                userInfo:userInfo
              },
              success:function(res){
                console.log(res)
              }
            })
          },
        })
        

      },
    })
  }

})